import axios from 'axios';
import * as actionTypes from './actionTypes';
import { fromJS } from 'immutable';

const changeHome = (data) => ({
    type: actionTypes.INIT_HOME,
    topicList: fromJS(data.topicList),
    articleList: fromJS(data.articleList),
    recommendList: fromJS(data.recommendList)
});

const loadMoreArticle = (list, nextPage) => ({
    type: actionTypes.LOAD_MORE_ARTICLE,
    list: fromJS(list),
    nextPage
});

const switchTopvisibility = (isShow) => ({
    type: actionTypes.SWITCH_TOP_VISIBILITY,
    showScroll: isShow
});

export const initHome = () => {
    return async (dispatch) => {
        try {
            const val = await axios.get("/mock/api/home.json");
            const data = val.data;
            if (data.success) {
                dispatch(changeHome(data.data));
            } else {
                console.error(data.msg);
            }
        } catch(e) {
            console.error("网络发送失败:" + e);
        }
    }
}

export const getMoreList = (articlePage) => {
    return async (dispatch) => {
        try {
            const val = await axios.get("/mock/api/articleList.json?page=" + articlePage);
            const data = val.data;
            if (data.success) {
                let basic = Math.ceil(Math.random()) * new Date().getTime();
                data.data.reverse().map((item) => item.id = item.id + basic);
                dispatch(loadMoreArticle(data.data, articlePage + 1));
            } else {
                console.error(data.msg);
            }
        } catch(e) {
            console.error("网络发送失败:" + e);
        }
    }
}



export const toggleTopShow = () => {
    return (dispatch) => dispatch(switchTopvisibility(true));
}

export const toggleTopHide = () => {
    return (dispatch) => dispatch(switchTopvisibility(false));
}